package com.lh_travel.lohas.base;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.lh_travel.lohas.R;
import com.lh_travel.lohas.interfaces.PermissionListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by aaron on 2018/6/2.
 */

public abstract class UnLazyBasefragment extends Fragment {

    public View convertView;
    private SparseArray<View> mViews;
    public MainApplication mApp;
    public Context mContext;
    private PermissionListener perListener;

    //声明AMapLocationClient类对象
    AMapLocationClient mLocationClient = null;
    AMapLocationClientOption mLocationOption = null;
    public AlertDialog dialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mApp = (MainApplication) getActivity().getApplication();

        mContext = getContext();

        convertView = inflater.inflate(getLayoutId(), container, false);
        mViews = new SparseArray<>();

        findView();
        initView();
        initData();
        return convertView;
    }

    /**
     * 加载页面布局文件
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 寻找控件
     */
    protected abstract void findView();

    /**
     * 加载要显示的数据
     */
    protected abstract void initData();

    /**
     * 让布局中的view与fragment中的变量建立起映射
     */
    protected abstract void initView();

    /**
     * fragment中可以通过这个方法直接找到需要的view，而不需要进行类型强转
     *
     * @param viewId
     * @param <E>
     * @return
     */
    protected <E extends View> E findViewByID(int viewId) {
        if (convertView != null) {
            E view = (E) mViews.get(viewId);
            if (view == null) {
                view = (E) convertView.findViewById(viewId);
                mViews.put(viewId, view);
            }
            return view;
        }
        return null;
    }

    public void showMessage(String msg) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }

    public AlertDialog showMyDialog(String title, String text, String confirm, String cancle, View.OnClickListener confirmListener) {

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

        View view = View.inflate(mContext, R.layout.dialog_tos, null);

        builder.setView(view);

        if (title != null && title.length() > 0) {
            TextView tv_title = view.findViewById(R.id.tv_title);
            tv_title.setText(title);
        }

        if (text != null && text.length() > 0) {
            TextView tv_content = view.findViewById(R.id.tv_content);
            tv_content.setText(text);
        }

        RelativeLayout rl_button = view.findViewById(R.id.rl_button);
        Button btn_cancle = view.findViewById(R.id.btn_cancle);
        Button btn_confirm = view.findViewById(R.id.btn_confirm);

        if (confirm != null && confirm.length() > 0) {
            btn_confirm.setText(confirm);

            btn_confirm.setOnClickListener(confirmListener);

        } else {
            btn_confirm.setVisibility(View.GONE);
        }

        if (cancle != null && cancle.length() > 0) {
            btn_cancle.setText(cancle);

            btn_cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });

        } else {
            btn_cancle.setVisibility(View.GONE);
        }

        if ((confirm == null || confirm.length() == 0) && (cancle == null || cancle.length() == 0)) {
            rl_button.setVisibility(View.GONE);
        }
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();

        return dialog;
    }

    /**
     * 假如申请的是单个权限,就可以在perListener.onGranted中处理,否则需要在onDenied中处理;
     *
     * @param permissionList
     * @param perListener
     */
    public void checkMyPermission(List<String> permissionList, PermissionListener perListener) {

        this.perListener = perListener;

        ArrayList<String> requestPermissionsList = new ArrayList<>();

        for (int i = 0; i < permissionList.size(); i++) {

            if (ContextCompat.checkSelfPermission(mContext, permissionList.get(i))
                    != PackageManager.PERMISSION_GRANTED) {
                //记录要申请权限的index

                requestPermissionsList.add(permissionList.get(i));
            }

        }

        if (requestPermissionsList.size() != 0) {

            String[] str = new String[requestPermissionsList.size()];

            String[] permissions = requestPermissionsList.toArray(str);

            UnLazyBasefragment.this.requestPermissions(permissions, 2);

        } else {
            perListener.hasPermission();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {

            case 2:

                ArrayList<Integer> deneyList = new ArrayList<>();

                if (grantResults.length > 0) {

                    for (int i = 0; i < grantResults.length; i++) {

                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {

                            deneyList.add(i);
                        }
                    }

                    if (deneyList.size() == 0) {

                        //全部都没被拒绝
                        perListener.onGranted();

                    } else {
                        perListener.onDenied(deneyList);
                    }

                } else {

                    for (int i = 0; i < grantResults.length; i++) {
                        deneyList.add(i);
                    }

                }

                break;
        }
    }

    public void autoLocation(AMapLocationListener mLocationListener) {

        //初始化定位
        mLocationClient = new AMapLocationClient(mContext);
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();

        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setHttpTimeOut(3000);
        mLocationOption.setInterval(2000);
        mLocationOption.setOnceLocation(true);

        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);

        if (null != mLocationClient) {
            mLocationClient.setLocationOption(mLocationOption);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mLocationClient != null) {
            mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
        }
    }
}
